﻿using System;

/*代表碰撞检测的结果*/
public enum CollideResult
{
	SnakeBody,
	Food,
	NoCollid,
}

/*代表一个显示区域*/
public class Screen
{
	//屏幕的宽度，高度，空白区域显示的字符
	private int width;
	private int height;
	private char blankElement;
	//储存所以屏幕像素的数组
	public PixelContent[,] pixels { get; private set; }
	
	//构造函数，根据给定的宽度，高度，空白字符，生成屏幕像素数组，并将数组中的所有像素初始化为空白像素
	public Screen(int width , int height , char blankElement)
	{
		if(width <= 0 || height <= 0)
        {
			return;
        }
		this.width = width;
		this.height = height;
		this.blankElement = blankElement;
		pixels = new PixelContent[width, height];

        for (int ix = 0; ix < width; ix++)
        {
            for (int iy = 0; iy < height; iy++)
            {
                pixels[ix, iy] = new PixelContent(this.blankElement, PixelContentType.Blank);
            }
        }

        //ResetPixels();
    }

	//刷新屏幕方法
	public void Display()
    {
		Console.Clear();
		for (int iy = 0; iy < height; iy++)
		{
			for (int ix = 0; ix < width; ix++)
			{
				Console.Write(pixels[ix, iy].element);
			}
			Console.Write("\n");
		}
	}

	//初始化所有像素
	private void ResetPixels()
    {
		for (int ix = 0; ix < width; ix++)
		{
			for (int iy = 0; iy < height; iy++)
			{
				pixels[ix, iy].SetPixelContent(blankElement, PixelContentType.Blank);
			}
		}
	}

	//清空蛇的像素
	public void ResetSnakePixels()
    {
		for (int ix = 0; ix < width; ix++)
		{
			for (int iy = 0; iy < height; iy++)
			{
				if(pixels[ix, iy].contentType == PixelContentType.SnakeBody)
                {
					pixels[ix, iy].SetPixelContent(blankElement, PixelContentType.Blank);
				}
			}
		}
	}

	//向像素数组中写入所有的蛇节点,并检测碰撞
	public CollideResult RenderSnake(SnakeBodyBlock[] snakeBody)
    {
		ResetSnakePixels();
		CollideResult result = CollideResult.NoCollid;


		for(int i = 0; i < snakeBody.Length; i++)
        {
			if(snakeBody[i] == null)
            {
				continue;
            }

			PixelContent currentPixel = pixels[snakeBody[i].x, snakeBody[i].y];
            switch (currentPixel.contentType)
            {
                case PixelContentType.SnakeBody:
                    result = CollideResult.SnakeBody;
					break;
                case PixelContentType.Food:
					if(result != CollideResult.SnakeBody)
                    {
						result = CollideResult.Food;
					}
					break;
                case PixelContentType.Blank:
					currentPixel.SetPixelContent(snakeBody[i].element, PixelContentType.SnakeBody);
					break;
                default:
                    break;
            }
        }
		return result;
    }

	public void RenderFood(Food food)
    {
		for (int ix = 0; ix < width; ix++)
		{
			for (int iy = 0; iy < height; iy++)
			{
				if (pixels[ix, iy].contentType == PixelContentType.Food)
				{
					pixels[ix, iy].SetPixelContent(blankElement, PixelContentType.Blank);
				}
			}
		}
		pixels[food.x, food.y].SetPixelContent(food.element, food.type);
    }
}
